package com.sup.servlet;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sup.entity.User;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static EntityManagerFactory emf;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init()
    {
    	emf = Persistence.createEntityManagerFactory("PersistenceUnit");
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EntityManager em = emf.createEntityManager();
		
		String username = (String)request.getParameter("username");
		String password = (String)request.getParameter("password");
		
		Query login = em.createQuery("SELECT count(*) FROM User user WHERE email='"+username+"'AND password='"+password+"'");
		long result = (long) login.getSingleResult();
		if(result == 1)
		{
			Query info = em.createQuery("SELECT user FROM User user WHERE email='"+username+"'");
			
			User user = (User) info.getSingleResult();
			request.getSession().setAttribute("idUser", user.getIdUser());
			request.getSession().setAttribute("admin", (int)user.getAdmin());
			request.getSession().setAttribute("username", user.getEmail());
			request.getSession().setAttribute("firstname", user.getFirstname());
			request.getSession().setAttribute("name", user.getName());

			response.sendRedirect(this.getServletContext().getContextPath() +"/index.jsp");
		}
		else
		{
			response.sendRedirect(this.getServletContext().getContextPath() +"/login.jsp");
		}
	}

}
